package com.akk.platform.oem.business;

import com.akk.module.avs.entity.AvsYbLoan;
import com.akk.module.avs.entity.AvsYbStep;
import com.akk.module.avs.model.request.AvsYbLoanRequest;
import com.akk.module.avs.model.response.AvsYbLoanRes;
import com.akk.module.avs.service.AvsYbLoanService;
import com.akk.utils.PageUtils;
import com.akk.utils.Query;
import com.akk.utils.RestResponse;
import com.akk.utils.ShiroUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class YbLoanBusiness {

    @Autowired
    private AvsYbLoanService ybLoanService;

    public RestResponse list(Query query, BindingResult bindingResult){
        if (bindingResult.hasErrors())
            return RestResponse.build("1",bindingResult.getFieldError().getDefaultMessage(),null);
        Map params = query.getSearch();
        params.put("appId", ShiroUtils.getAdmin().getAppId());
        PageHelper.startPage(query.getPage(),query.getLimit());
        List<AvsYbLoan> list = ybLoanService.findByParams(params);
        return RestResponse.build(PageUtils.buildPage(list,(int) new PageInfo<>(list).getTotal(),query));
    }

    public RestResponse save(AvsYbLoanRequest avsYbLoan){
        avsYbLoan.setAppId(ShiroUtils.getAdmin().getAppId());
        avsYbLoan.setCreateDate(new Date());
        ybLoanService.save(avsYbLoan);
        return RestResponse.build("200","success",null);
    }

    public RestResponse info(Long loanId){
        AvsYbLoanRes loan = ybLoanService.findById(loanId);
        if (loan == null)
            return RestResponse.build("1","信息不存在",null);
        List<Long> stepIds = new ArrayList<>();
        for (AvsYbStep step:loan.getSteps())
            stepIds.add(step.getStepId());
        loan.setStepIds(stepIds);
        loan.setSteps(null);
        return RestResponse.build(loan);
    }

    public RestResponse del(Long loanId){
        ybLoanService.delete(loanId);
        return RestResponse.build("200","success",null);
    }

    public RestResponse update(AvsYbLoanRequest loan){
        AvsYbLoanRes ybLoan = ybLoanService.findById(loan.getLoanId());
        if (ybLoan == null)
            return RestResponse.build("1","信息不存在",null);
        ybLoanService.update(loan);
        return RestResponse.build("200","success",null);
    }

}
